<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Expand;

class Feedplan extends Common
{

	/**
	 * 请求类型
	 *
	 * @return
	 */
	public function method(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedplan:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		if( in_array($sort, ['impression', 'clicks', 'cost', 'cash', 'rebate', 'copynumber', 'cpc', 'ctr', 'copycost']) ) {
			$sort = 's.'.$sort;
		} else {
			$sort = 'c.'.$sort;
		}

		array_push( $where, ['c.companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['c.userType', '=', 2 ] );

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['c.bazaarId', '=',  $bazaarId ] );
		}

		$userId = $request->param('userId', '', 'trim');
		if($userId) {
			array_push( $where, ['c.userId', '=',  $userId ] );
		}

		$status = $request->param('status', '', 'trim');
		if($status) {
			array_push( $where, ['c.status', '=',  $status ] );
		}

		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			$time = cloud_datetime_format( $createTimeStart, $createTimeEnd, true);
		} else {
			$time = cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), true);
		}

    $search = [];
		array_push( $search, " s.companyId = {$request->sessInfo['companyId']} ");
		array_push( $search, " s.userType = 2 ");
		array_push( $search, " s.campaignid > 0 ");
		array_push( $search, " c.campaignId = s.campaignid ");
	  array_push( $search, " s.datatime BETWEEN {$time[0]} AND {$time[1]} ");
    //权限管理
		$roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('feedauthaccount');
			if($authaccount) {
				array_push( $where, ['c.userid', 'in',  $authaccount ] );
			}
		}
		$query = Db::table('cfg_campaign')
		->alias('c')
		->field('c.id, c.bazaarId, c.status, c.userId, c.budget, c.campaignId, c.campaignName, c.schedule, c.regionName, c.datatime,
		  sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
	  ->leftJoin('cfg_search s', implode(' AND ', $search))
		->where($where)
		->group('c.campaignId')
		->order($sort, $order)
		->paginate($limit);

		$total = Db::table('cfg_campaign')
		->alias('c')
		->field('sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
		->leftJoin('cfg_search s', implode(' AND ', $search))
		->where($where)
		->find();

    // echo  Db::getLastSql() . "\n";
    $count = $query->total();
		$items = $query->items();
		foreach($items as &$value ) {
			$value['impression'] = $value['impression'] ? $value['impression'] : 0;
			$value['clicks'] = $value['clicks'] ? $value['clicks'] : 0;
			$value['cost'] = $value['cost'] ? $value['cost'] : 0;
			$value['cash'] = $value['cash'] ? $value['cash'] : 0;
			$value['rebate'] = $value['rebate'] ? $value['rebate'] : 0;
			$value['cpc'] = $value['cpc'] ? $value['cpc'] : 0;
			$value['ctr'] = $value['ctr'] ? $value['ctr'] : 0;
			$value['copynumber'] = $value['copynumber'] ? $value['copynumber'] : 0;
			$value['copycost'] = $value['copycost'] ? $value['copycost'] : 0;
			$value['userLevel'] = Db::table('cfg_expand')->where('userid', $value['userId'])->value('userLevel');
			$schedule = $value['schedule'] ? unserialize($value['schedule']) : [];
			$value['schedule'] = $schedule;
		}

		$total['impression'] = $total['impression'] ? $total['impression'] : 0;
		$total['clicks'] = $total['clicks'] ? $total['clicks'] : 0;
		$total['cost'] = $total['cost'] ? $total['cost'] : 0;
		$total['cash'] = $total['cash'] ? $total['cash'] : 0;
		$total['rebate'] = $total['rebate'] ? $total['rebate'] : 0;
		$total['cpc'] = $total['cpc'] ? $total['cpc'] : 0;
		$total['ctr'] = $total['ctr'] ? $total['ctr'] : 0;
		$total['copynumber'] = $total['copynumber'] ? $total['copynumber'] : 0;
		$total['copycost'] = $total['copycost'] ? $total['copycost'] : 0;
		return ['code'=> 0, 'msg'=> '', 'count'=> $count, 'data'=> $items, 'total' => $total,
			'expand' => Expand::getList($request->sessInfo, 2),
			'bazaar' => Bazaar::getList($request->sessInfo, 2)];
	}

	/**
	* 同步百度官方计划
	*
	* @param tValue
	* @return
	*/
	public function getCampaignFeed(Request $request) {
		if($this->hasPermission($request->sessInfo, 'feedplan:cloud')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$userId = $request->param('userId', '', 'trim');
		if( empty($userId) ) {
			return ['code'=> 403, 'msg'=> '请选择要同步的账号!'];
		}

		$obj = Expand::getUserInfo($request->sessInfo, $userId, 2);
		if(!is_object($obj)) {
			return ['code'=> 403, 'msg'=> '数据异常,请稍后重试!'];
		}

		$response = doPostRequest('https://api.baidu.com/json/feed/v1/CampaignFeedService/getCampaignFeed', json_encode([
			'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
			'body'=> [
        "campaignFeedFields"=> [
            "campaignFeedId",
            "campaignFeedName",
            "budget",
            "status",
        ]
			]
		]));

		if(empty($response)) {
			return json(['code'=> 403, 'msg'=> 'network anomaly detection.!']);
		}

		$result = json_decode ($response, true);
		if(!isset($result['header']['desc'])){
			return json(['code'=> 403, 'msg'=> 'network anomaly detection.!']);
		}

		if(!isset($result['header']['desc'])) {
			return json(['code'=> 403, 'msg'=> 'network anomaly detection.!']);
		}

		if($result['header']['desc'] == 'failure') {
			$tempMessage  = explode('sn:', $result['header']['failures'][0]['message']);
			return json(['code'=> 403, 'msg'=> 'code: ' . $result['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] ]);
		}

	  $campaignFeedIdArray = [];
    if(is_array($result['body']['data'])) {
			foreach($result['body']['data'] as $value) {
				array_push($campaignFeedIdArray, $value['campaignFeedId']);
				$value['budget'] = isset($value['budget']) ? $value['budget'] : 0;
				$campaignId = Db::table('cfg_campaign')->where('companyId', $request->sessInfo['companyId'])
				  ->where('campaignId', $value['campaignFeedId'])->value('id');
				if($campaignId) {
					Db::name('cfg_campaign')->where('campaignId', $value['campaignFeedId'])->update([
						'bazaarId' => $obj->bazaarId,
						'campaignName' =>  $value['campaignFeedName'],
						'budget' => $value['budget'],
						'datatime' => date('Y-m-d H:i:s'),
						'status' => $value['status'],
					]);
				} else {
					Db::name('cfg_campaign')->insert([
					  'companyId' => $request->sessInfo['companyId'],
						'userType' => 2,
						'userId' => $userId,
						'bazaarId' => $obj->bazaarId,
						'budget' => $value['budget'],
						'datatime' => date('Y-m-d H:i:s'),
						'campaignId' => $value['campaignFeedId'],
						'campaignName' => $value['campaignFeedName'],
						'status' => $value['status']
					]);
				}
			}

			// 清除已删除计划
			Db::table('cfg_campaign')->where('companyId', $request->sessInfo['companyId'])->where('userType', 2)->where('userId', $userId)
			  ->whereNotIn('campaignid', $campaignFeedIdArray)->delete();

			// 清除不存在计划
			Db::table('cfg_search')->where('companyId', $request->sessInfo['companyId'])->where('userType', 2)->where('userid', $userId)
			  ->where('campaignid', '>', 0)->whereNotIn('campaignid', $campaignFeedIdArray)->delete();
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>[]]);
	}

	/**
	* 计划执行地址
	*
	* @param tValue
	* @return
	*/
	private function updateCampaignFeed($parameter) {
		$request = doPostRequest('https://api.baidu.com/json/feed/v1/CampaignFeedService/updateCampaignFeed', $parameter);
		if(empty($request)) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		$result = json_decode ($request, true);
		if(!isset($result['header']['desc'])){
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		if(!isset($result['header']['desc'])) {
			return ['header'=>['desc'=>'failure', 'failures'=> [[ 'code' => 0, 'message' => 'network anomaly detection.' ]]]] ;
		}
		return $result;
	}

	/**
	 * 设置计划每日预算
	 *
	 * @return
	 */
	public function setBudget(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedplan:budget')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

    $handleId = [];

		$ids = $request->param('selectId/a', '', 'trim');
		if(is_array($ids)) {
			foreach($ids as $id) {
				if($id) {
					array_push($handleId, $id);
				}
			}
		}

		$id = $request->param('id', '', 'trim');
		if($id) {
			$handleId = [];
			array_push($handleId, $id);
		}

		if(count($handleId) === 0){
			return ['code'=>403, 'msg'=>'请选择要设置的计划!'];
		}

		$budgetType = $request->param('budgetType/d', '', 'trim');
		$budget = $request->param('budget/d', '', 'trim');
		if( $budgetType === 0 ) {
			$budget = 0;
		}

		$result = [];
		$beginTime = microtime(true);
		$query = Db::table('cfg_campaign')->field('id, userId, campaignId, campaignName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $handleId)->group('campaignId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 2);
				if(is_object($obj)) {
					$response = $this->updateCampaignFeed(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'campaignFeedTypes'=>[
								[
									"campaignFeedId"=> $value['campaignId'],
									"budget"=> $budget,
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						Db::name('cfg_campaign')->where('campaignId', $value['campaignId'])->update(['budget' => $budget]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '信息流计划报告', '设置计划每日预算, ' . $budget . '元', 0, null);
						array_push($result, '['.$value['campaignName'].'] 操作成功.');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '['.$value['campaignName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] );
					}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}


	/**
	 * 设置计划状态
	 *
	 * @return
	 */
	public function setPause(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedplan:userStat')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$selectId = $request->param('selectId/a', '', 'trim');
		if( count($selectId) == 0 ) {
			return ['code'=> 403, 'msg'=> '请选择要设置的计划!'];
		}

		$result = [];
		$beginTime = microtime(true);
		$pause = $request->param('pause/d', '', 'trim');
		$query = Db::table('cfg_campaign')->field('id, userId, campaignId, campaignName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $selectId)->group('campaignId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 2);
				if(is_object($obj)) {
					$response = $this->updateCampaignFeed(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'campaignFeedTypes'=>[
								[
									"campaignFeedId"=> $value['campaignId'],
									"pause"=> $pause
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						$campaignFeed = doPostRequest('https://api.baidu.com/json/feed/v1/CampaignFeedService/getCampaignFeed', json_encode([
							'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=> $obj->token],
							'body'=> [
								"campaignFeedFields"=> [
										"status"
								]
							]
						]));
						if( $campaignFeed ) {
							$campaignJson = json_decode ($campaignFeed, true);
							if( isset($campaignJson['body']['data'][0]) ){
								Db::name('cfg_campaign')->where('campaignId', $campaignJson['body']['data'][0]['campaignFeedId'])->update(['status' => $campaignJson['body']['data'][0]['status']]);
							}
						}
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '信息流计划报告', '设置计划状态, ' . $pause, 0, null);
						array_push($result, '['.$value['campaignName'].'] 操作成功.');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '['.$value['campaignName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] );
					}
				}
			}
		}
		return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=>$result]);
	}


	/**
	 * 设置计划推广时段
	 *
	 * @return
	 */
	public function setHour(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedplan:schedule')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

    $handleId = [];

		$ids = $request->param('selectId/a', '', 'trim');
		if(is_array($ids)) {
			foreach($ids as $id) {
				if($id) {
					array_push($handleId, $id);
				}
			}
		}

		$id = $request->param('id', '', 'trim');
		if($id) {
			$handleId = [];
			array_push($handleId, $id);
		}

		if(count($handleId) === 0) {
			return ['code'=>403, 'msg'=>'请选择要设置的计划!'];
		}

		$result = [];
		$beginTime = microtime(true);
		$scheduleName = '自定义时段';
		$hourType = $request->param('hourType', '', 'trim');
		$schedule = $request->param('schedule/a', '', 'trim');
		if($hourType == 0 || count($schedule) == 168) {
			$schedule = [];
			$scheduleName = '全部时段';
		}

    $_schedule = [];
		for ($i=1; $i<=7; $i++) {
			$startHour = [];
			foreach($schedule as $key => $value) {
				if($value['weekDay'] == $i) {
					array_push($startHour, $value['startHour']);
				}
			}
			$algorithm = getAlgorithm($startHour, $i);
			if (is_array($algorithm)) {
				foreach($algorithm as $value) {
					array_push($_schedule, $value);
				}
			}
		}

		array_multisort (array_column($_schedule, 'weekDay'), SORT_ASC, $_schedule);

		$query = Db::table('cfg_campaign')->field('id, userId, campaignId, campaignName')->where('companyId', $request->sessInfo['companyId'])
		->where('id', 'in', $handleId)->group('campaignId')->select()->toArray();
		if( is_array($query)) {
			foreach($query as $value) {
				$obj = Expand::getUserInfo($request->sessInfo, $value['userId'], 2);
				if(is_object($obj)) {
					$response = $this->updateCampaignFeed(json_encode([
						'header'=>['username'=> $obj->username, 'password'=>$obj->password, 'token'=>$obj->token],
						'body'=> [
							'campaignFeedTypes'=> [
								[
									"campaignFeedId"=> $value['campaignId'],
									"schedule"=> $_schedule
								]
							]
						]
					]));
					if($response['header']['desc'] == 'success') {
						Db::name('cfg_campaign')->where('campaignId', $value['campaignId'])->update(['schedule' => serialize($schedule)]);
						$endTime = microtime(true);
						$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '信息流计划报告', '设置计划推广时段, ' . $scheduleName, 0, null);
						array_push($result, '<i class="el-message__icon el-icon-success"></i><span style="vertical-align:top;">['.$value['campaignName'].'] 操作成功.</span>');
					} else {
						$tempMessage  = explode('sn:', $response['header']['failures'][0]['message']);
						array_push($result, '<i class="el-message__icon el-icon-error"></i><span style="vertical-align:top;">['.$value['campaignName'].'] 操作失败, code: ' . $response['header']['failures'][0]['code'] . ' message: ' . $tempMessage[0] . '</span>');
					}
				}
			}
		}
    return json(['code'=> 0, 'msg'=> '操作成功!', 'data'=> $result]);
	}

}
